package com.example.webdemo.controller;

import com.example.webdemo.bean.Product;
import com.example.webdemo.common.ApiResult;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zp
 * @version 1.0
 * @description: TODO
 * @date 2023/7/22 17:59
 */
@RestController
public class DemoController {
    private static List<Product> list;
    static {
        list = new ArrayList<>();
        list.add(new Product(1,"香蕉",3,10,1,10));
        list.add(new Product(2,"苹果",5,20,1,20));
        list.add(new Product(3,"小西瓜",7,9,1,9));
        list.add(new Product(4,"草莓",9,50,1,50));
        list.add(new Product(5,"榴莲",10,70,1,70));
    }

    @RequestMapping(value = "/getProduct",method = RequestMethod.GET)
    public ApiResult getProduct(){
        return ApiResult.success(list);
    }

    @RequestMapping(value = "/addProduct",method = RequestMethod.POST)
    public ApiResult addProduct(@RequestBody Product product){
        Integer maxId = list.stream().map(Product::getId).max(Integer::compareTo).get();
        product.setId(maxId+1);
        list.add(product);
        return ApiResult.success();
    }

    @RequestMapping(value = "/editProduct",method = RequestMethod.POST)
    public ApiResult editProduct(@RequestBody Product product){
        Product oldProduct = list.stream().filter(p -> p.getId() == product.getId()).findFirst().orElse(null);
        if(Objects.isNull(oldProduct)){
            return ApiResult.fail("编辑商品不存在");
        }
        BeanUtils.copyProperties(product, oldProduct);
        return ApiResult.success();
    }

    @RequestMapping(value = "/deleteProduct",method = RequestMethod.POST)
    public ApiResult deleteProduct(@RequestBody Product product){
        List<Integer> ids = list.stream().map(Product::getId).collect(Collectors.toList());
        int id = product.getId();
        if(ids.contains(id)){
            Product productById = list.stream().filter(p -> p.getId()==id).findFirst().get();
            list.remove(productById);
            return ApiResult.success();
        }
        return ApiResult.fail("删除失败 删除的商品不存在");
    }
}
